<template>
  <t-card>
    <t-space direction="vertical" style="width: 100%">
      <t-form v-show="showSearch" ref="queryRef" :data="queryParams" layout="inline" reset-type="initial" label-width="calc(4em + 12px)">
        
        <t-form-item label="代理商名称" name="agentName">
          <t-input v-model="queryParams.agentName" placeholder="请输入代理商名称" clearable @enter="handleQuery" />
        </t-form-item>
        <t-form-item label="订单号" name="orderId">
          <t-input v-model="queryParams.orderId" placeholder="请输入订单号" clearable @enter="handleQuery" />
        </t-form-item>
        <t-form-item label="分佣金额（元)" name="profitAmount">
          <t-input v-model="queryParams.profitAmount" placeholder="请输入分佣金额" clearable @enter="handleQuery" />
        </t-form-item>
        <t-form-item label="关联结算单号" name="settlementId">
          <t-input v-model="queryParams.settlementId" placeholder="请输入关联结算单号" clearable @enter="handleQuery" />
        </t-form-item>
        
        <t-form-item label="分佣日期" name="profitTime">
          <t-date-picker
            v-model="queryParams.profitTime"
            allow-input
            clearable
            placeholder="请选择"
          />
        </t-form-item>
        <t-form-item label="结算状态" name="status">
          <t-select v-model="queryParams.status" placeholder="请选择结算状态" clearable>
            <t-option label="未结算" value="0" />
            <t-option label="已结算" value="1" />
          </t-select>
        </t-form-item>
       
        <t-form-item label-width="0px">
          <t-button theme="primary" @click="handleQuery">
            <template #icon> <search-icon /></template>
            搜索
          </t-button>
          <t-button theme="default" @click="resetQuery">
            <template #icon> <refresh-icon /></template>
            重置
          </t-button>
        </t-form-item>
      </t-form>

      <t-table
        v-model:column-controller-visible="columnControllerVisible"
        :loading="loading"
        hover
        row-key="recordId"
        :data="profitRecordList"
        :columns="columns"
        :selected-row-keys="ids"
        select-on-row-click
        :pagination="pagination"
        :column-controller="{
          hideTriggerButton: true,
        }"
        @select-change="handleSelectionChange"
      >
        <template #topContent>
          <t-row>
            <t-col flex="auto">
              <t-button v-hasPermi="['system:profitRecord:export']" theme="default" variant="outline" @click="handleExport">
                <template #icon> <download-icon /> </template>
                导出
              </t-button>
              <t-button v-hasPermi="['system:profitRecord:settle']" theme="primary" variant="outline" @click="handleBatchSettle">
                批量结算
              </t-button>
              <span class="selected-count">已选 {{ ids.length }} 项</span>
            </t-col>
            <t-col flex="none">
              <t-button theme="default" shape="square" variant="outline" @click="showSearch = !showSearch">
                <template #icon> <search-icon /> </template>
              </t-button>
              <t-button theme="default" variant="outline" @click="columnControllerVisible = true">
                <template #icon> <setting-icon /> </template>
                列配置
              </t-button>
            </t-col>
          </t-row>
        </template>
        <template #operation="{ row }">
          <t-space :size="8" break-line>
            <my-link v-hasPermi="['system:profitRecord:query']" @click.stop="handleDetail(row)">
              <template #prefix-icon><browse-icon /></template>详情
            </my-link>
            <t-button 
              v-hasPermi="['system:profitRecord:settle']" 
              v-if="String(row.status) !== '1'"
              theme="primary" 
              size="small" 
            >
              结算
            </t-button>
          </t-space>
        </template>
      </t-table>
    </t-space>


    <!-- 分佣记录详情 -->
    <t-dialog
      v-model:visible="openView"
      header="分佣记录详情"
      placement="center"
      width="min(700px, 100%)"
      attach="body"
      :footer="false"
    >
      <my-descriptions :loading="openViewLoading">
        <t-descriptions-item label="记录id">{{ form.recordId }}</t-descriptions-item>
        <t-descriptions-item label="代理商id">{{ form.agentId }}</t-descriptions-item>
        <t-descriptions-item label="代理商名称">{{ form.agentName }}</t-descriptions-item>
        <t-descriptions-item label="订单号">{{ form.orderId }}</t-descriptions-item>
        <t-descriptions-item label="分佣金额（元)">{{ form.profitAmount }}</t-descriptions-item>
        <t-descriptions-item label="关联结算单号">{{ form.settlementId }}</t-descriptions-item>
        <t-descriptions-item label="分佣备注" :span="2">{{ form.note }}</t-descriptions-item>
        <t-descriptions-item label="">{{ parseTime(form.profitTime) }}</t-descriptions-item>
        <t-descriptions-item label="状态">{{ String(form.status) === '1' ? '已结算' : '未结算' }}</t-descriptions-item>
        <t-descriptions-item label="">{{ parseTime(form.createdAt) }}</t-descriptions-item>
        <t-descriptions-item label="创建时间">{{ parseTime(form.createTime) }}</t-descriptions-item>
        <t-descriptions-item label="更新时间">{{ parseTime(form.updateTime) }}</t-descriptions-item>
      </my-descriptions>
    </t-dialog>
  </t-card>
</template>
<script lang="ts" setup>
defineOptions({
  name: 'ProfitRecord',
});
import {
  BrowseIcon,
  DownloadIcon,
  RefreshIcon,
  SearchIcon,
  SettingIcon,
} from 'tdesign-icons-vue-next';
import type { FormInstanceFunctions, FormRule, PageInfo, PrimaryTableCol, SubmitContext,  } from 'tdesign-vue-next';
import { computed, getCurrentInstance, ref } from 'vue';
import { ArrayOps } from '@/utils/array';

import type { SysProfitRecordQuery, SysProfitRecordVo } from '@/api/system/model/profitRecordModel';
import { listProfitRecord, getProfitRecord, delProfitRecord } from '@/api/system/profitRecord';

const { proxy } = getCurrentInstance();

const openView = ref(false);
const openViewLoading = ref(false);
const profitRecordList = ref<SysProfitRecordVo[]>([]);
const loading = ref(false);
const columnControllerVisible = ref(false);
const showSearch = ref(true);
const total = ref(0);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);


// 列显隐信息
const columns = ref<Array<PrimaryTableCol>>([
  { title: `选择列`, colKey: 'row-select', type: 'multiple', width: 50, align: 'center' },
  { title: `代理商id`, colKey: 'agentId', align: 'center' },
  { title: `代理商名称`, colKey: 'agentName', align: 'center' },
  { title: `订单号`, colKey: 'orderId', align: 'center' },
  { title: `分佣金额（元)`, colKey: 'profitAmount', align: 'center' },
  { title: `关联结算单号`, colKey: 'settlementId', align: 'center' },
  { title: `分佣备注`, colKey: 'note', align: 'center', ellipsis: true },
  { title: ``, colKey: 'profitTime', align: 'center', minWidth: 112, width: 180 },
  { title: `结算状态`, colKey: 'status', align: 'center', cell: (h, { row }) => {
    return String(row.status) === '1' ? '已结算' : '未结算';
  } },
  { title: ``, colKey: 'createdAt', align: 'center', minWidth: 112, width: 180 },
  { title: `创建时间`, colKey: 'createTime', align: 'center', minWidth: 112, width: 180 },
  { title: `更新时间`, colKey: 'updateTime', align: 'center', minWidth: 112, width: 180 },
  { title: `操作`, colKey: 'operation', align: 'center', width: 180 },
]);
// 提交表单对象
const form = ref<SysProfitRecordVo>({});
// 查询对象
const queryParams = ref<SysProfitRecordQuery>({
  pageNum: 1,
  pageSize: 10,
  agentId: undefined,
  agentName: undefined,
  orderId: undefined,
  profitAmount: undefined,
  settlementId: undefined,
  note: undefined,
  profitTime: undefined,
  status: undefined,
  createdAt: undefined,
});
// 分页
const pagination = computed(() => {
  return {
    current: queryParams.value.pageNum,
    pageSize: queryParams.value.pageSize,
    total: total.value,
    showJumper: true,
    onChange: (pageInfo: PageInfo) => {
      queryParams.value.pageNum = pageInfo.current;
      queryParams.value.pageSize = pageInfo.pageSize;
      getList();
    },
  };
});

/** 查询分佣记录列表 */
function getList() {
  loading.value = true;
  listProfitRecord(queryParams.value)
    .then((response) => {
      profitRecordList.value = response.rows;
      total.value = response.total;
    })
    .finally(() => (loading.value = false));
}

// 表单重置
function reset() {
  form.value = {};
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm('queryRef');
  handleQuery();
}

/** 多选框选中数据 */
function handleSelectionChange(selection: Array<string | number>) {
  ids.value = selection;
  single.value = selection.length !== 1;
  multiple.value = !selection.length;
}


/** 详情按钮操作 */
function handleDetail(row: SysProfitRecordVo) {
  reset();
  openView.value = true;
  openViewLoading.value = true;
  const recordId = row.recordId;
  getProfitRecord(recordId).then((response) => {
    form.value = response.data;
    openViewLoading.value = false;
  });
}


/** 结算按钮操作 */
function handleSettle(row: SysProfitRecordVo) {
  proxy.$modal.confirm(`是否确认结算分佣记录编号为${row.recordId}的数据项？`, () => {
    const msgLoading = proxy.$modal.msgLoading('正在结算中...');
    // 这里需要调用结算接口，暂时用提示代替
    return Promise.resolve()
      .then(() => {
        proxy.$modal.msgSuccess('结算成功');
        getList();
      })
      .finally(() => {
        proxy.$modal.msgClose(msgLoading);
      });
  });
}

/** 批量结算按钮操作 */
function handleBatchSettle() {
  if (ids.value.length === 0) {
    proxy.$modal.msgWarning('请选择要结算的记录');
    return;
  }

  // 获取选中的记录
  const selectedRecords = profitRecordList.value.filter(record => 
    ids.value.includes(record.recordId)
  );
  
  // 检查是否都是同一个代理商
  const agentIds = [...new Set(selectedRecords.map(record => record.agentId))];
  if (agentIds.length > 1) {
    proxy.$modal.msgWarning('只能结算同一个代理商的记录');
    return;
  }

  const agentId = agentIds[0];
  const recordIds = selectedRecords.map(record => record.recordId);
  
  proxy.$modal.confirm(`是否确认结算代理商 ${agentId} 的 ${recordIds.length} 条记录？`, () => {
    const msgLoading = proxy.$modal.msgLoading('正在批量结算中...');
    // 这里需要调用批量结算接口，暂时用提示代替
    return Promise.resolve()
      .then(() => {
        proxy.$modal.msgSuccess('批量结算成功');
        getList();
        ids.value = []; // 清空选择
      })
      .finally(() => {
        proxy.$modal.msgClose(msgLoading);
      });
  });
}

/** 删除按钮操作 */
function handleDelete(row?: SysProfitRecordVo) {
  const recordIds = row?.recordId || ids.value;
  proxy.$modal.confirm(`是否确认删除分佣记录编号为${recordIds}的数据项？`, () => {
    const msgLoading = proxy.$modal.msgLoading('正在删除中...');
    return delProfitRecord(recordIds)
      .then(() => {
        ids.value = ArrayOps.fastDeleteElement(ids.value, recordIds);
        getList();
        proxy.$modal.msgSuccess('删除成功');
      })
      .finally(() => {
        proxy.$modal.msgClose(msgLoading);
      });
  });
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download(
    'system/profitRecord/export',
    {
      ...queryParams.value,
    },
    `profitRecord_${new Date().getTime()}.xlsx`,
  );
}

getList();
</script>
